/**
 *
 * 声音的基础类
 * 子类复写loadedPlay()方法，异步加载成功后执行该方法
 * http://edn.egret.com/cn/docs/page/156
 * 声音文件推荐：码率 44100Hz 96kbs ；工具推荐 格式工厂
 */
class BaseSound extends BaseClass{
    /** 正在加载的资源 */
    public loadingCache: Array<string>;
    
    /** 默认为声音全开0 - 1之间 */
    public volume:number;
    
	public constructor() {
    	  super();
        this.loadingCache = new Array<string>();
        this.volume = 1;
        //资源过期处理 TODO
	}
	
	/**
	 * 是否已经缓存
	 */ 
	public isCache(source:string):boolean{
        var sound = this.getSound(source);  
        return sound != null;
	}
	
	/**
	 * 判断音乐是否在加载中，网不好的情况调用
	 */ 
	public isSoundResLoading(source:string):boolean{
        var index = this.loadingCache.indexOf(source);
        return index != -1;
	}
	
	/**
	 * 播放音乐
	 * @param source 音乐资源的位置
	 * @param loop 是否循环，小于等于0无限循环,默认循环
	 */ 
	public play(source:string,loop?:number):void{
        var sound = this.getSound(source);  
        this.playSound(sound,loop);
	}
	
	/**
	 * 播放音乐
	 * @param sound 音乐对象
	 * @param loop 是否循环，小于等于0无限循环
	 */ 
    public playSound(sound: egret.Sound,loop?: number):void{
        if(sound) {
            var soundChannel = sound.play(0,loop);
            soundChannel.volume = this.volume;
            Log.d("Play Sound,Loop:"+loop +",Volume:"+this.volume);
        } else {
            Log.d("Excute PlaySound(),Sound AsyncLoad ");
        }
    }
	
	/**
	 * 获取声音处理对象
	 */ 
    public getSound(source : string) :egret.Sound{
        var sound:egret.Sound = RES.getRes(source);
    	  //如果未定义，即还没有load资源，开始load资源
        if(!sound){
            Log.d("Sound Async Load");
            this.loadingCache.push(source);
            RES.getResAsync(source , this.onSoundResLoadComplete , this);
        }else{
            Log.d("Sound has RES");
        }
        return sound;
	}
	
    public onSoundResLoadComplete(data:any ,key:string):void{
        Log.d("SoundResLoadComplete:\"" + key+"\"");
        var index: number = this.loadingCache.indexOf(key);
        if(index != -1){
            this.loadingCache.splice(index,1);
            this.loadedPlay(key);
        }else{
            Log.d("Please Load Config");
        }
    }
	/**
	 * 子类复写该方法，异步加载成功资源后执行该方法
	 * @param source 资源名称
	 */ 
    public loadedPlay(source:string):void{
        Log.d("Excute LoadedPlay(" + source+")");
    }
	
    
	public static test(){
        var soundLoad = new BaseSound();
        var sound:egret.Sound = soundLoad.getSound("bg_intro_1_mp3");
//        soundLoad.play("bg_intro_1_mp3",1);
        soundLoad.volume = 0.1;
        soundLoad.playSound(sound,1); 
         
	}
	
}
